<?php

App::uses('AppController', 'Controller');

class PaymentsController extends AppController {
    
    public $pageTitle = "Uplate";
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE
    );
    
    public $uses = array('Payment');
    
    public function index() {
        $filter = $this->parseFilterData('Payment');
        
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";
        $payments = $this->paginate('Payment', $filter->conditions);
        
        $this->set(compact('payments'));
        $this->setFilterData($filter);
    }
    
    public function create() {
        $data = $this->Payment->create();
        
        $campaign = @$this->params->query['campaign'];
        if (! empty($campaign)) {
            $campaign = $this->Payment->Campaign->findById($campaign);
            $campaign['Campaign']['Location'] = $campaign['Location'];
            $campaign['Campaign']['Client'] = $campaign['Client'];
            $data['Campaign'] = Set::extract('Campaign', $campaign);
        }
                
        $this->set(compact('data', 'campaign'));
        $this->render('form');
    }
    
    public function edit($id) {
        $data = $this->Payment->findById($id);
        $c = $this->Payment->Campaign->findById($data['Campaign']['id']);
        $data['Campaign']['Location'] = $c['Location'];
        $data['Campaign']['Client'] = $c['Client'];
        
        $this->set('data', $data);
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Payment->create($data);
            
            if (! $this->Payment->validates()) {
                $this->set('data', $data);
                $this->setFlash('Uneti podaci nisu validni.');
                return $this->render('form');
            }
            
            if (! $this->Payment->save($data)) {
                $this->set('data', $data);
                $this->setFlash('Čuvanje nije uspelo.');
                return $this->render('form');
            }

            $this->setFlash('Uplata je uspešno sačuvana.', 'ok');
            $this->redirect('edit/' . $this->Payment->id);
        }
        
        $this->redirect('index');
    }
    
    public function remove($id) {
        if ($this->Payment->delete($id)) {
            $this->setFlash('Uplata je uspešno obrisana.', 'ok');
        }else{
            $this->setFlash('Uplata nije obrisana.');
        }
        $this->redirect('index');
    }
    
}
